<script setup>
import { inject } from 'vue';
import DeepChild from './DeepChild.vue';

// 从父组件注入数据
const theme = inject('theme');
const toggleTheme = inject('toggleTheme');
</script>

<template>
  <div class="provide-inject-demo">
    <div class="injected-data">
      <h4>注入的数据</h4>
      <p>当前主题: <span class="theme-value">{{ theme }}</span></p>
      <button class="theme-btn" @click="toggleTheme">
        在中间组件中切换主题
      </button>
    </div>
    
    <div class="nested-components">
      <h4>深层嵌套组件</h4>
      <div class="component-tree">
        <div class="tree-level">
          <span class="level-label">中间组件</span>
          <DeepChild />
        </div>
      </div>
    </div>
    
    <div class="explanation">
      <h4>Provide/Inject 说明</h4>
      <ul>
        <li>👆 根组件使用 provide 提供数据</li>
        <li>👇 深层子组件直接使用 inject 获取数据</li>
        <li>🔄 无需通过 props 逐层传递</li>
        <li>💡 特别适合深层组件树的数据共享</li>
      </ul>
    </div>
  </div>
</template>

<style scoped>
.provide-inject-demo {
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
}

.injected-data {
  background: #fff3cd;
  padding: 1rem;
  border-radius: 8px;
  border: 1px solid #ffeaa7;
}

.injected-data h4 {
  color: #856404;
  margin-bottom: 0.5rem;
}

.theme-value {
  font-weight: bold;
  padding: 0.2rem 0.5rem;
  background: rgba(0, 0, 0, 0.1);
  border-radius: 4px;
}

.theme-btn {
  background: #856404;
  color: white;
  border: none;
  padding: 0.5rem 1rem;
  border-radius: 6px;
  cursor: pointer;
  margin-top: 0.5rem;
  transition: background 0.3s ease;
}

.theme-btn:hover {
  background: #6c5203;
}

.nested-components {
  background: #d1ecf1;
  padding: 1rem;
  border-radius: 8px;
  border: 1px solid #bee5eb;
}

.nested-components h4 {
  color: #0c5460;
  margin-bottom: 0.5rem;
}

.component-tree {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 1rem;
}

.tree-level {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 0.5rem;
}

.level-label {
  font-weight: 500;
  color: #0c5460;
  background: white;
  padding: 0.3rem 0.8rem;
  border-radius: 4px;
}

.explanation {
  background: #f8d7da;
  padding: 1rem;
  border-radius: 8px;
  border: 1px solid #f5c6cb;
}

.explanation h4 {
  color: #721c24;
  margin-bottom: 0.5rem;
}

.explanation ul {
  list-style: none;
  padding: 0;
}

.explanation li {
  padding: 0.3rem 0;
  color: #721c24;
  font-size: 0.95rem;
}
</style>